package com.replication.support;

import com.replication.constants.DBType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * Created by yangshoujun on 2016/3/7 10:34.
 */

@Aspect
@Component
public class MasterSlaveSelectAspect {

    @Around("@annotation(master)")
    public Object invoke(final ProceedingJoinPoint proceedingJoinPoint, Master master) throws Throwable {

        DBType old = DBSelectContext.get();
        try {
            // 执行前切换到主库
            DBSelectContext.set(DBType.MASTER);
            Object result = proceedingJoinPoint.proceed();
            return result;
        } finally {
            // 执行完后恢复到之前的库
            DBSelectContext.set(old);
        }
    }
}
